/**
 * 
 */
package org.cuatrovientos.erp.dao;

import java.util.List;

import org.cuatrovientos.erp.model.User;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

/**
 * implementation of UserDAOInterface
 * @author pablo_guerrero
 *
 */
public class UserDAO implements UserDAOInterface{
	
	@Autowired
	 private SessionFactory sessionFactory;
	
	/**
	 * default Constructor
	 */
	public UserDAO(){
		
	}
	
	/**
	 * returns Hibernate session
	 * @return the session
	 */
	 private Session getSession(){
		 return sessionFactory.getCurrentSession();
	 }
	
	 /**
	  * @param int id
	  * @return the user
	  */
	@Override
	@Transactional(readOnly = true)
	public User selectById(int id) {
		User user = (User) getSession().get(User.class, id);
	    return user;
	}
	
	/**
	 * @return all the users we have
	 */
	@Override
	@Transactional(readOnly = true)
	public List<User> selectAll() {
		List<User> users = getSession().createQuery("from User").list();
	    return users;
	}

	/**
	 * @return the number of users in database
	 */
	@Transactional(readOnly = true)
	public int selectAllCount() {
		List<User> users = getSession().createQuery("from User").list();
	    return users.size();
	}
	
	/**
	 * @param User user
	 * This method insert a role in the database passed by parameter
	 */
	@Override
	@Transactional
	public void insert(User user) {
		Integer id = (Integer) getSession().save(user);
		user.setId(id);  
		
	}
	
	/**
	 * @param User user
	 * This method updates an user passed by parameter
	 */
	@Override
	@Transactional
	public void update(User user) {
		getSession().merge(user);		
	}

	/**
	 * @param User user
	 * This method deletes an user passed by parameter
	 */
	@Override
	@Transactional
	public void delete(User user) {
		getSession().delete(user);
	}
	
	/**
	 * @param User user
	 * 
	 */
	public void saveOrUpdate(User user){
			getSession().saveOrUpdate(user);
	}
	
	/**
	 * @param int id
	 * This method deletes the user selected by id
	 */
	@Override
	@Transactional(readOnly=true)
	public void deleteById(int id) {
		User user = (User) getSession().load(User.class,id);
		getSession().delete(user);
	}
	
	/**
	 * @param  String name
	 * This method searches all the users which has the same name we are looking for.
	 */
	@Override
	@Transactional(readOnly=true)
	public List<User> search(String name) {
		 Query query = getSession().createQuery("from User u where u.name like :name");
         query.setParameter("name", "%"+name+"%");
         List<User> users = query.list();
		
         return users;
	}

}
